package com.wh.wisdomsite.xbox.server.controller.st;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.st.ContractDetailIn;
import com.wh.wisdomsite.xbox.pojo.st.ContractIn;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.Contract;
import com.wh.wisdomsite.xbox.st.entity.ContractDetail;
import com.wh.wisdomsite.xbox.st.entity.Material;
import com.wh.wisdomsite.xbox.st.service.IContractDetailService;
import com.wh.wisdomsite.xbox.st.service.IContractService;
import com.wh.wisdomsite.xbox.st.service.IMaterialService;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 合同清单Controller
 *
 * @version V1.0
 * @Package: package com.wh.wisdomsite.xbox.server.controller.pr
 * @author: 蔡道行
 * @date: 2018-08-08 10:17
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping(value = "/contractDetail")
public class ContractDetailController {

    private static final Log logger = LogFactory.getLog(ContractDetailController.class);

    @Autowired
    private IContractService iContractService;

    @Autowired
    private IContractDetailService iContractDetailService;

    @Autowired
    private IMaterialService iMaterialService;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 页面跳转
     *
     * @return
     */
    @RequiresPermissions("rules:st_contractDetail_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index() {
        return "/st/contractDetail/contractDetailList";
    }

    /**
     * 页面跳转
     *
     * @return
     */
    @RequiresPermissions("rules:st_contractDetail_page")
    @RequestMapping(value = "contractDetailInventoryListIndex.do", method = RequestMethod.GET)
    public String contractDetailInventoryListIndex(String coId,HttpServletRequest request) {
        try {
            request.setAttribute("coId", coId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "/st/contractDetail/contractDetailInventoryList";
    }

    /**
     * 获取合同清单集合
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:st_contractDetail_find")
    @RequestMapping(value = "/contractDetailList.do")
    public void contractDetailList(HttpServletResponse response, ContractDetailIn in) {
        try {
            logger.info("加载合同清单数据列表-->>开始");
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<ContractDetail> page = new Page<ContractDetail>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<ContractDetail> ewContractDetail = new EntityWrapper<ContractDetail>();
            ewContractDetail.setEntity(new ContractDetail());
            //根据项目名称查询
            if (StringUtils.isNotEmpty(in.getPrName())) {
                ewContractDetail.like("p.prName", in.getPrName());
            }
            //根据合同名称查询
            if (StringUtils.isNotEmpty(in.getCoName())) {
                ewContractDetail.like("co.coName", in.getCoName());
            }
            //根据合同编号查询
            if (StringUtils.isNotEmpty(in.getCoNumber())) {
                ewContractDetail.like("co.coNumber", in.getCoNumber());
            }
            //根据合同ID查询
            if(StringUtils.isNotEmpty(in.getCoId())){
                ewContractDetail.eq("co.coId",in.getCoId());
            }

            //根据物料名称查询
            if (StringUtils.isNotEmpty(in.getMaterialName())) {
                ewContractDetail.like("ma.materialName", in.getMaterialName());
            }
            //根据合同编号查询
            if (StringUtils.isNotEmpty(in.getStandardType())) {
                ewContractDetail.like("ma.standardType", in.getStandardType());
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewContractDetail = UserUtils.setEntityWrapper(ewContractDetail, "c1", "o1", "p");
            }
            ewContractDetail.orderBy("createDate", false);
            Page<Map<String,Object>> contractDetailPage = iContractDetailService.getMapsPage(page,ewContractDetail);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (contractDetailPage.getRecords().size() > 0) {
                for (Map<String, Object> contractDetail : contractDetailPage.getRecords()) {
                    JSONObject object = new JSONObject(contractDetail);
                    object.put("id", contractDetail.get("cdId"));
                    if(contractDetail.get("material")!=null){
                        object.put("maId",((Material)contractDetail.get("material")).getMaId());
                        object.put("materialName",((Material)contractDetail.get("material")).getMaterialName());
                        object.put("brand",((Material)contractDetail.get("material")).getBrand());
                        object.put("standardType",((Material)contractDetail.get("material")).getStandardType());
                        object.put("technicalParameter",((Material)contractDetail.get("material")).getTechnicalParameter());
                        object.put("meteringUnit",((Material)contractDetail.get("material")).getMeteringUnit());
                        object.put("unitPrice",((Material)contractDetail.get("material")).getUnitPrice());
                        object.put("characterization",((Material)contractDetail.get("material")).getCharacterization());
                    }
                    if(contractDetail.get("project")!=null){
                        object.put("prName",((Project)contractDetail.get("project")).getPrName());
                    }
                    if(contractDetail.get("contract")!=null){
                        object.put("coName",((Contract)contractDetail.get("contract")).getCoName());
                        object.put("coNumber",((Contract)contractDetail.get("contract")).getCoNumber());
                    }
                    array.put(object);
                }
            }
            json.put("total", contractDetailPage.getTotal());
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载合同清单数据列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载合同清单数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 合同详情
     * @param contractIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:st_contractDetail_view")
    @RequestMapping("/contractDesc.do")
    public String contractDesc(ContractIn contractIn, HttpServletRequest request) {
        try {
            logger.info("合同详情-->>开始");
            Map<String,Object> contract = iContractService.getMapById(contractIn.getCoId());
            if(contract.get("createBy") != null){
                contract.put("createBy", UserMapManager.getUserLoginNameInMap(contract.get("createBy").toString()));
            }
            if(contract.get("updateBy") != null){
                contract.put("updateBy", UserMapManager.getUserLoginNameInMap(contract.get("updateBy").toString()));
            }
            request.setAttribute("contract", contract);
            logger.info("合同详情-->>结束");
        }catch (Exception e){
            logger.debug("合同详情-->>Exception" + e.getMessage());
            e.printStackTrace();
        }
        return "/st/contractDetail/contractDesc";
    }

    /**
     * 合同清单详情
     * @param contractDetailIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:st_contractDetail_view")
    @RequestMapping("/contractDetailDesc.do")
    public String contractDetailDesc( ContractDetailIn contractDetailIn, HttpServletRequest request) {
        try {
            logger.info("合同清单详情-->>开始");
            Map<String,Object> contractDetail = iContractDetailService.getMapById(contractDetailIn.getCdId());
            if(contractDetail.get("createBy") != null){
                contractDetail.put("createBy", UserMapManager.getUserLoginNameInMap(contractDetail.get("createBy").toString()));
            }
            if(contractDetail.get("updateBy") != null){
                contractDetail.put("updateBy", UserMapManager.getUserLoginNameInMap(contractDetail.get("updateBy").toString()));
            }
            request.setAttribute("contractDetail", contractDetail);
            request.setAttribute("coId",contractDetailIn.getCoId());
            logger.info("合同清单详情-->>结束");
        }catch (Exception e){
            logger.debug("合同清单详情-->>Exception" + e.getMessage());
            e.printStackTrace();
        }
        return "/st/contractDetail/contractDetailDesc";
    }

    /**
     * 跳转至添加或修改页面
     *
     * @return
     */
    @RequestMapping("/toContractDetail.do")
    public ModelAndView toAddActivity(String cdId, HttpServletRequest request) {
        logger.info("添加修改合同清单跳转-->>开始");
        Map<String,Object> contractDetail = null;
        if(StringUtils.isNotEmpty(cdId)){
            //contractDetail
            contractDetail = iContractDetailService.getMapById(cdId);
            request.setAttribute("contractDetail", contractDetail);
        }
        logger.info("添加修改合同清单跳转-->>开始");
        return new ModelAndView("st/contractDetail/contractDetailEdit");
    }

    /**
     * 更新或者修改
     * @param contractDetail
     * @param response
     */
    @RequiresPermissions("rules:st_contractDetail_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(ContractDetail contractDetail, HttpServletResponse response) {
        try {
            //判断方法是否已经存在,存在即更新.否则为添加
            if (StringUtils.isNotEmpty(contractDetail.getCdId())){
                logger.info("修改合同清单-->>开始");
                contractDetail.setTotalPrice((contractDetail.getMaterial().getUnitPrice())*(contractDetail.getTotalCount()));
                contractDetail.setUpdateBy(UserUtils.getCurrentUser().getUsId());
                contractDetail.setUpdateDate(new Date());
                iContractDetailService.updateById(contractDetail);
                if(null!=contractDetail.getMaterial()){
                    iMaterialService.updateById(contractDetail.getMaterial());
                }
                logger.info("修改合同清单-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("合同清单更新成功"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("操作合同清单-->>Exception" + e.getMessage());
        }
    }

    /**
     * 删除合同清单
     *
     * @param
     * @param response
     */
    @RequiresPermissions("rules:st_contractDetail_del")
    @RequestMapping(value = "/del.do", method = RequestMethod.GET)
    public void del(String cdId, HttpServletResponse response) {
        try {
            logger.info("删除合同清单-->>开始");
            iContractDetailService.deleteById(cdId);
            logger.info("删除合同清单-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("合同清单删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除合同清单-->>Exception" + e.getMessage());
        }
    }

    /**
     * 跳转至添加页面
     * @return
     */
    @RequestMapping("/toContractDetailAdd")
    public String toContractDetailAdd(HttpServletRequest request,String coId){
        logger.info("添加合同清单跳转-->>开始");
        if(StringUtils.isNotEmpty(coId)){
            request.setAttribute("coId",coId);
        }
        logger.info("添加合同清单跳转-->>结束");
        return "st/contractDetail/contractDetailAdd";
    }

    /**
     * 添加保存
     * @param contract
     * @param response
     */
    @RequiresPermissions("rules:st_contractDetail_add")
    @RequestMapping(value = "/addSave.do", method = RequestMethod.POST)
    public void addSave(Contract contract, HttpServletRequest request, HttpServletResponse response){
        try {
            logger.info("添加合同清单-->>开始");
            String userId = UserUtils.getCurrentUser().getUsId();
            iContractDetailService.saveContractDetail(contract,request,userId);
            logger.info("添加合同清单-->>结束");
            response.getWriter().write(JsonUtil_Org.returnTrue("合同清单添加成功"));
        }catch (Exception e){
            e.printStackTrace();
            try{
                response.getWriter().write(JsonUtil_Org.returnFalse("合同清单添加异常，请联系管理员！"));
            }catch (Exception e1){
            }
            logger.debug("操作合同清单-->>Exception" + e.getMessage());
        }
    }

}
